package com.syyo.admin.utils;


import com.syyo.admin.domain.entity.DeptEntity;
import com.syyo.admin.domain.resp.MenuResp;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: wangzhong
 * @Date: 2019/9/12 15:21
 * @Description: 树形结构
 */
public class TreeUtils {

    /**
     * 菜单转换树形结构
     *
     * @param list
     * @return
     */
    public static List<MenuResp> listToMenuTree(List<MenuResp> list) {
        //用递归找子。
        List<MenuResp> treeList = new ArrayList<>();
        for (MenuResp tree : list) {
            if (tree.getPid() == 0) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }

    //寻找子节点
    private static MenuResp findChildren(MenuResp tree, List<MenuResp> list) {
        for (MenuResp node : list) {
            if (node.getPid().equals(tree.getMenuId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<MenuResp>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }

    /**
     * 部门转换树形结构
     *
     * @param list
     * @return
     */
    public static List<DeptEntity> listToDeptTree(List<DeptEntity> list) {
        //用递归找子。
        List<DeptEntity> treeList = new ArrayList<>();
        for (DeptEntity tree : list) {
            if (tree.getPid() == 0) {
                treeList.add(findChildren(tree, list));
            }
        }
        return treeList;
    }

    //寻找子节点
    private static DeptEntity findChildren(DeptEntity tree, List<DeptEntity> list) {
        for (DeptEntity node : list) {
            if (node.getPid().equals(tree.getDeptId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<DeptEntity>());
                }
                tree.getChildren().add(findChildren(node, list));
            }
        }
        return tree;
    }
}
